import React, { useEffect, useState } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
import { Swiper, Tabs, Toast } from 'antd-mobile'
import axios from 'axios';
import { LeftOutline } from 'antd-mobile-icons'
import Goodsdetail from '../components/detail/Goodsdetail'
import Comments from '../components/detail/Comments'
import { connect } from 'react-redux';

function Detail(props) {
    let {username, password} = JSON.parse(localStorage.getItem('token'));
    const navigate = useNavigate();
    const {id} = useParams();
    let {show, hidden} = props;
    const [goodlist, setGoodList]= useState();
    const tabList = ['商品详情', '用户评价'];
    useEffect(()=>{
        axios(`/goods/${id}`).then(res=>{
            setGoodList(res.data);
        })
    },[id])
    useEffect(()=>{
      hidden();
      return ()=>{
        show();
      }
    })
    const addToCart = () =>{
      axios(`/carts?goodId=${id}&username=${username}&password=${password}`).then(res=>{
        if(res.data.length){
          axios.patch(`/carts/${res.data[0].id}`,{
            number: res.data[0].number + 1
          })
        }
        else{
          axios.post(`/carts`,{
            username: username,
            password: password,
            goodId: id,
            number: 1,
            checked: false
          })
        }
        Toast.show({
          content: '哇！谢谢主人喜欢我！',
        })
      })
    }
  return (
    <div>
      <LeftOutline style={{fontSize:'1.3rem', position:'fixed', top:'.2rem', zIndex:10}} onClick={()=>{
        window.history.back()
      }}/>
      <Swiper autoplay loop>
        {goodlist && goodlist.slides.map(item => 
            <Swiper.Item key={item} style={{display:"flex", justifyContent:'center'}}>
              <img style={{height:'12rem'}} src={`http://localhost:5000/${item}`} alt='加载失败'/>
            </Swiper.Item>
          )}
      </Swiper>
      <Tabs>
        {
          tabList.map((item, index)=>
          <Tabs.Tab title={item} key={item}>
            {index === 0? <Goodsdetail goodlist={goodlist}/>: <Comments/>}
          </Tabs.Tab>
        )}
      </Tabs>
      <div style={
        {
         height:'3.0625rem', 
         lineHeight:'3.0625rem', 
         width:'100%', 
         textAlign:'center', 
         display:'flex', 
         position:'fixed', 
         bottom:0, 
         color:'white', 
         fontSize:'1.2rem', 
         fontWeight:'bold'
        }
      }>
        <span style={{flex:'1', height:'100%', backgroundColor:'orange'}} onClick={()=>{
          navigate(`/auth/shopping`)
        }}>跳转购物袋</span>
        <span style={{flex:'1', height:'100%', backgroundColor:'red'}} onClick={()=>{
          addToCart();
        }}>加入购物袋</span>
      </div>
    </div>
  )
}

const mapDispatchToProps = {
  show(){
    return {
      type:'tabbar-show'
    }
  },
  hidden(){
    return {
      type:'tabbar-hidden'
    }
  }
}

export default connect(null, mapDispatchToProps)(Detail);